from flask import render_template
from flask_login import login_required
from . import analysis
from ..models import Device
from sqlalchemy import func
from datetime import datetime, timedelta

@analysis.route('/analysis')
@login_required
def analysis_index():
    # 获取设备类型统计
    device_type_stats = Device.query.with_entities(
        Device.device_type,
        func.count(Device.id).label('count')
    ).group_by(Device.device_type).all()
    
    # 获取设备状态统计
    status_stats = Device.query.with_entities(
        Device.status,
        func.count(Device.id).label('count')
    ).group_by(Device.status).all()
    
    # 获取最近添加的设备
    recent_devices = Device.query.order_by(Device.created_at.desc()).limit(5).all()
    
    # 获取在线设备比例
    total_devices = Device.query.count()
    online_devices = Device.query.filter_by(status='online').count()
    online_ratio = (online_devices / total_devices * 100) if total_devices > 0 else 0
    
    return render_template('analysis/index.html',
                         device_type_stats=device_type_stats,
                         status_stats=status_stats,
                         recent_devices=recent_devices,
                         online_ratio=online_ratio,
                         title='数据分析') 